<?php namespace Common\Model;
use Hdphp\Model\Model;

class Goods extends Model{
	private $pmodel;
	private $smodel;
//	指定表
	protected $table="goods";
//	自动验证，固定写法
	protected $validate=array(
		array('gname','require','商品名称不能为空',3,3),
//		array('market','required','市场价不能为空',3,3),
		array('cheap','required','商城价不能为空',3,3),
	);
//	自动完成
//	1是在插入时候处理；3，是必须处理的表单
	protected $auto = array(
		array('registertime','time','function',3,1),
		array('coding','coding','method',3,1),
	);
	
//处理货号	
	public function coding(){
		$coding=mt_rand(1,100000);
		return $coding;
	}
	
	
//	添加
	public function store(){
		$gid=Q('get.gid',0,'intval');
//		实例化商品属性表
		$this->smodel= new shopnature;
//		验证商品表数据
		if(!$this->create()) return false;
//		执行添加
//		添加并返回商品id
		$gid=$this->add();		
//		商品属性表添加
		$this->smodel->shopvalue($gid);
//		给商品详细添加数据并添加商品表的id
		$this->pmodel->data['goods_gid']=$gid;
		$this->add();
		
//		2.给商品详情表添加数据
		$gid = $this->add();
		$detailModel=new \Common\Model\product;
		$detailModel->create();
		$detailModel->data['goods_gid']=$gid;
//		//把数组变为字符串，把多张图片压入到数据库
		$detailModel->data['bigdrawing']=implode('|', Q('post.bigdrawing',array()));
		$detailModel->add();

		return true;
		
	}
	
//编辑模型
	public function edit(){
		$gid=Q('post.gid',0,'intval');
		if(!$this->create()) return false;
		//1修改商品表
//		p($_POST);die;
		$this->data['listing']=Q('post.listing');
		$this->save();
		//2修改商品详细表
		
		$detailModel=new \Common\Model\product;
		//把数组变为字符串，把多张图片压入到数据库
		
		$detailModel->data['bigdrawing']=Q('post.bigdrawing');
		$detailModel->data['bigdrawing']=implode('|', Q('post.bigdrawing',array()));
		$detailModel->data['goodsdetail']=Q('post.goodsdetail');
		$detailModel->data['aftersale']=Q('post.aftersale');
		$detailModel->where("goods_gid=$gid")->save();

		//3修改表article_tag
		//先删除
		$attrModel=new \Common\Model\shopnature;
		$attrModel->where("goods_gid=$gid")->delete();
		//再添加
//		p($_POST);die;
		//规格添加
		foreach (Q('post.spec',array()) as $k => $v){
			if(isset($v['value'])){
				foreach ($v['value'] as $kk => $vv) {
					if(!empty($vv)){
						$add = array(
							'shopvalue' => $vv,
							'shopprice'   => $v['price'][$kk],
							'nature_nid' => $k,
							'goods_gid' => $gid
						);
						$attrModel->add($add);	
					}			
				}
			}
			
		}
		//属性添加
		foreach (Q('post.attr',array()) as $k=>$v){
			if(!empty($v)){
				$data=array(
					'shopvalue'=>$v,
					'nature_nid' => $k,
					'goods_gid' => $gid
				);
				$attrModel->add($data);	
			}		
		}
		return true;
	}

}

	











